package servlet.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import pojo.User;
import service.UserLoginService;
import service.UserRegisterService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/register")
public class UserRegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求体的字符编码为UTF-8，防止中文乱码
        req.setCharacterEncoding("UTF-8");
        // 从请求体中获取 JSON 格式的数据
        StringBuilder requestBody = new StringBuilder();
        BufferedReader reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            requestBody.append(line);
        }
        // 使用 FastJSON 将 JSON 格式的数据转换为 Java 对象
        User user = JSON.parseObject(requestBody.toString(), User.class);
        // 调用注册服务处理注册逻辑
        UserRegisterService registerService = new UserRegisterService();
        int code = registerService.searchUser(user.getUsername(),user.getPassword(),user.getPhone());
        // 将结果返回给前端
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("{\"code\":" + code + "}");
        writer.flush();
    }
}
